package com.ht.yml.tools;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author wangmin
 * @discription
 * @created 2025-01-02 10:43
 */
public class ApplicationConfigUtils {
    public static Map<String, Object> generateApplicationConfigMapByYmlFile(final String env) {
        String application_fileName = Const.configFileBaseDir+"application.yml";
        String applicationEnv_fileName = Const.configFileBaseDir+"application-"+env+".yml";
        final Map<String, Object> applicationConfigMap = YamlReader.readFiles(application_fileName, applicationEnv_fileName);

        /*System.out.println("applicationConfigMap:");
        String yamlStr = YamlReader.dump(applicationConfigMap);
        System.out.println(yamlStr);*/
        return applicationConfigMap;
    }

    public static Map<String, Object> generateApplicationConfigMapByPropertyFile(final String env) throws Exception {
        String application_fileName = Const.configFileBaseDir+"application.properties";
        String applicationEnv_fileName = Const.configFileBaseDir+"application-"+env+".properties";

        Map<String, String> applicationProperties = readPropertyFile(application_fileName);
        Map<String, String> applicationEnvProperties = readPropertyFile(applicationEnv_fileName);
        Map<String, String> applicationMergedProperties = new HashMap<>(applicationProperties.size()+applicationEnvProperties.size());
        applicationMergedProperties.putAll(applicationProperties);
        applicationMergedProperties.putAll(applicationEnvProperties);

        Map<String, Object> applicationConfigMap = YamlPropertiesUtils.convertProperties2YmlMap(applicationMergedProperties);

        /*System.out.println("applicationConfigMap:");
        String yamlStr = YamlReader.dump(applicationConfigMap);
        System.out.println(yamlStr);*/
        return applicationConfigMap;
    }
    public static Map<String, String> readPropertyFile(String filePath) throws FileNotFoundException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            return readPropertyFile(fis);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    public static Map<String, String> readPropertyFile(InputStream is) {
        Properties properties = new Properties();
        try {
            Reader reader = new InputStreamReader(is, "UTF-8");
            properties.load(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, String> valueMap = new HashMap<>(properties.stringPropertyNames().size());
        for (String key : properties.stringPropertyNames()) {
            valueMap.put(key, properties.getProperty(key));
        }
        return valueMap;
    }
}
